package com.github.llyb120.sxmanage;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.func.Func1;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;

/**
 * @Author: Administrator
 * @Date: 2020/12/15 16:17
 */
public class Util {

    public static Process RunScript(String script, boolean async){
        File temp = null;
        Process process = null;
        try{
            temp = File.createTempFile("abc", "def");
            temp.deleteOnExit();
            FileUtil.writeString(script, temp, StandardCharsets.ISO_8859_1);
            System.out.println(temp.getAbsolutePath());
            process = Runtime.getRuntime().exec("sh " + temp.getAbsolutePath());
            if(!async){
                process.waitFor();
            }
            return process;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(!async){
                if (process != null) {
                    process.destroy();
                }
            }
        }
        return null;
    }

    public static String HandleScript(String script){
        script = StrUtil.replace(script, "\\$\\{(.+?)\\}", new Func1<Matcher, String>() {
            @Override
            public String call(Matcher parameter) throws Exception {
                String token = parameter.group(1);
                try{
                    return WebSocketConfig.environment.getProperty(token);
                } catch (Exception e){
                    return "";
                }
            }
        });
        script = script.replaceAll("\r", "");
        return script;
    }
}
